package prv.pursuivant.armory.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.w3c.dom.Document;

import prv.pursuivant.armory.Cache;
import prv.pursuivant.armory.DOMLeecher;
import prv.pursuivant.armory.DOMParser;
import prv.pursuivant.armory.Importer;
import prv.pursuivant.config.ImporterDesc;
import prv.pursuivant.core.AllAchievements;
import prv.pursuivant.core.AllToons;
import prv.pursuivant.core.Toon;
import prv.pursuivant.core.ToonAchievements;
import prv.pursuivant.core.impl.AllAchievementsImpl;

import com.google.inject.Inject;

public class ArmoryImporter implements Importer {

	protected final ImporterDesc desc;
	protected final Cache cache;
	protected final DOMLeecher leecher;
	protected final DOMParser parser;

	/**
	 * @param desc
	 */
	@Inject
	public ArmoryImporter(ImporterDesc desc, Cache cache, DOMLeecher leecher,
			DOMParser parser) {
		this.desc = desc;
		this.cache = cache;
		this.leecher = leecher;
		this.parser = parser;
	}

	@Override
	public ToonAchievements readAchievements(Toon toon) throws IOException {
		ToonAchievements achievs;
		try {
			achievs = cache.read(toon);
		} catch (IOException e) {
			// just ignore cache writing problems
			achievs = null;
			// TODO: some logging here later
		}
		if (achievs != null)
			return achievs;
		Document dom = leecher.getDOM(toon.getName());
		achievs = parser.parseDOM(toon, dom);
		try {
			cache.write(toon, achievs);
		} catch (IOException e) {
			// just ignore cache writing problems
			// TODO: some logging here later
		}
		return achievs;
	}

	@Override
	public AllAchievements readAllAchievements(AllToons toons)
			throws IOException {
		Map<String, ToonAchievements> achievements = new HashMap<String, ToonAchievements>();
		for (Toon toon : toons) {
			final ToonAchievements toonAchievs = readAchievements(toon);
			achievements.put(toon.getName(), toonAchievs);
		}
		return new AllAchievementsImpl(achievements);
	}
}
